package com.samnative.pineapple.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.samnative.pineapple.adapter.BankcardAdapter;
import com.samnative.pineapple.entity.BankcardModel;
import com.samnative.pineapple.entity.UserModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.GsonUtils;
import com.google.gson.reflect.TypeToken;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.shashank.sony.fancytoastlib.FancyToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理我的银行卡
 */
public class BankcardManagerActivity extends BaseActivity implements
        OnClickListener, BaseQuickAdapter.OnItemClickListener {

    /**
     * 适配器
     */
    private BankcardAdapter adapter;
    /**
     * 地址列表
     */
    private RecyclerView rlv_content;
    /**
     * 没有数据时显示的textview
     */
    private LinearLayout ll_nodata;
    /**
     * 判断点击操作是选择还是编辑
     */
    private boolean isSelect = true;
    /**
     * 管理按钮
     */
    private TextView tv_manager;
    /**
     * 添加OR解绑按钮
     */
    private TextView tv_add_bankcard;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bankcard_manager;
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        isSelect = getIntent().getBooleanExtra("isSelect", true);
        find(R.id.tv_back).setOnClickListener(this);
        tv_add_bankcard = (TextView) find(R.id.tv_add_bankcard);
        tv_add_bankcard.setOnClickListener(this);
        tv_manager = (TextView) find(R.id.tv_manager);
        tv_manager.setOnClickListener(this);
        ll_nodata = (LinearLayout) find(R.id.ll_nodata);

        adapter = new BankcardAdapter(R.layout.item_bankcard_manager);
        adapter.setOnItemClickListener(this);
        rlv_content = find(R.id.rlv_content);
        rlv_content.setLayoutManager(new LinearLayoutManager(mContext));
        rlv_content.setAdapter(adapter);

        if (isSelect) {
            tv_manager.setVisibility(View.GONE);
            // tv_add_bankcard.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_add_bankcard:
                if (tv_add_bankcard.getText().toString().equals("解绑")) {
                    int index = adapter.getIndex();
                    if (index >= 0) {
                        requestUnbindCard(adapter.getData().get(index));
                    } else {
                        FancyToast.showToast(mContext, "请选中一张银行卡", FancyToast.WARNING, false);
                    }
                } else {
                    UserModel model = AppPrefer.getUserModel(mContext);
                    if (model != null && model.getData().getIsnameauth().equals("0")) {


                        MessageDialog.show(this, null, "请完成实名认证", getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                                new OnDialogButtonClickListener() {
                                    @Override
                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                        Intent intent2 = new Intent().setClass(mContext, AuthNameActivity.class);
                                        startActivity(intent2);
                                        return false;
                                    }
                                });


                        return;
                    }

                    if (model != null && model.getData().getIsnameauth().equals("2")) {
                        FancyToast.showToast(mContext, "实名认证审核中", FancyToast.INFO, false);
                        return;
                    }

                    startActivity(new Intent(mContext, AddBankcardActivity.class));
                }

                break;
            case R.id.tv_manager:
                if (adapter.getData().size() == 0) {
                    break;
                }
                if (tv_manager.getText().toString().equals("管理")) {
                    tv_add_bankcard.setText("解绑");
                    tv_manager.setText("取消");
                    adapter.setManager(true);
                } else {
                    tv_add_bankcard.setText("添加银行卡");
                    tv_manager.setText("管理");
                    adapter.setManager(false);
                    adapter.setIndex(-1);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 获取银行卡列表
     */
    private void dataInit() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("_apiname", "user.user.banklist");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post((Activity) mContext, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {

                try {
                    JSONObject jsonData = result
                            .getJSONObject("data");
                    JSONArray jsonArray = jsonData.getJSONArray("list");
                    if (jsonArray.length() > 0) {
                        List<BankcardModel> temp = GsonUtils.fromJsonList(
                                jsonArray.toString(),
                                new TypeToken<List<BankcardModel>>() {
                                }.getType());
                        adapter.getData().clear();
                        adapter.addData(temp);
                        rlv_content.setVisibility(View.VISIBLE);
                        ll_nodata.setVisibility(View.GONE);
                        tv_manager.setVisibility(View.VISIBLE);
                    } else {
                        rlv_content.setVisibility(View.GONE);
                        ll_nodata.setVisibility(View.VISIBLE);
                        tv_manager.setVisibility(View.GONE);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

    }

    /**
     * 解绑银行卡
     */
    private void requestUnbindCard(BankcardModel model) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("_apiname", "user.user.unband");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        map.put("bank_id", model.getId());
        HttpRequest.post((Activity) mContext, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {

                FancyToast.showToast(mContext, "解绑成功", FancyToast.SUCCESS, false);
                tv_add_bankcard.setText("添加银行卡");
                tv_manager.setText("管理");
                adapter.setIndex(-1);
                dataInit();
            }
        });

    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        dataInit();
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapterr, View view, int position) {
        if (isSelect) {
            Intent intent = new Intent();
            intent.putExtra("address", adapter.getData().get(position));
            setResult(101, intent);
            finish();
        } else {
            adapter.setIndex(position);
        }
    }
}
